import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable } from '@nestjs/common';
import { type Cache } from 'cache-manager';
import * as svgCaptcha from 'svg-captcha';
const TTL = 5 * 60 * 1000;
@Injectable()
export class CaptchaService {
  constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
  async getCaptcha(clientId: string) {
    const captcha = svgCaptcha.create({
      size: 4,
      ignoreChars: '0o1i', // 排除容易混淆的字符
      noise: 2, // 干扰线数量
      color: true, // 彩色验证码
      background: '#f0f0f0', // 背景色
      width: 100, // 宽度
      height: 40, // 高度
    });
    await this.cacheManager.set(
      'captcha_' + clientId,
      captcha.text.toLowerCase(),
      TTL,
    );
    return {
      data: `data:image/svg+xml;base64,${Buffer.from(captcha.data).toString('base64')}`,
    };
  }

  validateCaptcha(text: string, captcha: string) {
    return text.toLowerCase() === captcha.toLowerCase();
  }
}
